#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8
# vim:tabstop=4
#
# Copyright (c) 2010 by xkhhdx
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import configure
from django.utils import simplejson
#import json as simplejson
import re
import bitly

add_pic_url = True

def make_limit_string(str,lim,trim):
    if len (str) + len(trim) > lim-1:
        str = str[0:lim-len(trim)-1] +u"…"
    str = str + trim
    return str

def parse_tweet(str):
    #print str.replace("}","}<br>\n") # .replace(">",">");
    ret = []

    timeline = simplejson.loads(str)

    return timeline

def cook_tweet(tweetdict, source = u"新浪", charlimit = 140):
    #print str.replace("}","}<br>\n") # .replace(">",">");
    ret = []

    #for current_tweet in timeline:
    current_tweet = tweetdict
    if current_tweet:
        try:
            tmp = current_tweet["retweeted_status"]
        except KeyError:
            isret = False
        except TypeError:
            isret = False
            #current_tweet = current_tweet[0]
        else:
            isret = True
        try:
            str = current_tweet["text"] # 这里是内容

            if add_pic_url:
                try:
                    pic_url = current_tweet["original_pic"]
                    short = configure.bitlyapi.shorten(pic_url)
                    current_tweet["original_pic"] = short
                    str = make_limit_string(str,140, u"[图："+ short.replace(r"http://","") + u"]")

                except Exception,e:
                    print "Error pos:original_pic_url_shortenning", e
                    pass

            if isret==True:
                str = str + ur" 转自：@" + current_tweet["retweeted_status"]["user"]["name"] + u"：" + current_tweet["retweeted_status"]["text"]


                if add_pic_url:
                    try:
                        pic_url = current_tweet["retweeted_status"]["original_pic"]
                        #api = bitlyapi.Api(login='xkhhdx', apikey='R_b9cf5d8b32a52ba39820c51034f995f9')
                        short = configure.bitlyapi.shorten(pic_url)
                        current_tweet["retweeted_status"]["original_pic"] = short
                        str = make_limit_string(str,140, u"[图："+ short.replace(r"http://","") + u"]")
                    except Exception,e:
                		#raise e
                        print "Error pos:retweeted_status_original_pic_url_shortenning", e
                        pass


            html_mark=re.compile('</?\w+[^>]*>') # HTML标签
            str = make_limit_string(str,140, u" via " + source + "-"+ html_mark.sub("",current_tweet["source"]) + u"通道");
            current_tweet["text"] = str

            ret.append((current_tweet["id"],str))

        except Exception,e:
            print "ERRR",e
            pass

    return tweetdict

if __name__ == '__main__':
    import urllib2
    print "get json string..."
    print "connecting..."
    timeline_uri="http://api.t.sina.com.cn/statuses/user_timeline/%s.json?source=%s&count=5"
    print "downloading json..."
    jsonstr = urllib2.urlopen(timeline_uri).read()
    print "start parse..."
    parse_tweet(jsonstr)#[0]["retweeted_status"]["original_pic"]  #[4]['text']



